﻿#include"CompilerProject.h"


void InitKeywords(TkWord keywords[], int keywordsLen, pTkWord* tk_Hashtable) {
	for (int i = 0; i < keywordsLen - 1; ++i) {
		InsertHashElement(tk_Hashtable, keywords[i].spelling, keywords[i].tkcode);
	}
}

//查找元素
pTkWord SeekElement(pTkWord hashTable[], char* data) {
	pTkWord pos = hashTable[elf_hash(data)];
	if (NULL == pos)
		return NULL;
	else {
		while (pos)
		{
			if (strcmp(pos->spelling, data) == 0)
			{
				return pos;
			}
			pos = pos->next;
		}
	}
}
//通过hash函数计算以后，字符串就可以变为一个整型数，值是0-999
int elf_hash(char* key)
{
	int h = 0, g;
	while (*key)
	{

		h = (h << 4) + *key++;
		g = h & 0xf0000000;
		if (g)
			h ^= g >> 24;//g>>24只要高4位key的低4位也存在但是为0
		h &= ~g;
	}
	return h % MAXHASHVOLUME;
}
int InsertHashElement(pTkWord hashTable[], char* data, tokencode tkcode) {
	int pos = elf_hash(data);
	if (NULL == hashTable[pos])
	{
		pTkWord temp = (pTkWord)calloc(1, sizeof(TkWord));
		if (temp)
		{
			temp->next = NULL;
			if (temp->spelling = (char*)calloc(strlen(data) + 1, sizeof(char)))
			{
				strcpy(temp->spelling, data);
			}
			if (tkcode>=0)
			{
				temp->tkcode = tkcode;
			}
			hashTable[pos] = temp;
		}
	}
	else {
		if (HashConflict(hashTable[pos], data, tkcode))
			return 0;
		return pos;
	}
	return pos;
}
int HashConflict(pTkWord p, char* data, tokencode tkcode) {
	pTkWord pre = p;
	while (p)
	{
		if (strcmp(p->spelling, data) == 0)
		{
			return SameElement();
		}
		pre = p;
		p = p->next;
	}
	pTkWord temp = (pTkWord)calloc(1, sizeof(TkWord));
	if (temp)
	{
		temp->next = NULL;
		if (temp->spelling = (char*)calloc(strlen(data) + 1, sizeof(char)))
		{
			strcpy(temp->spelling, data);
			temp->tkcode = tkcode;
		}
		pre->next = temp;
	}
	return 0;
}
//建表遇到相同元素的处理方式
int SameElement() {
	return 1;
}